package bootstrap

import (
	"fmt"
	"github.com/crazyhl/gopermission/models"
	"github.com/urfave/cli/v2"
	"go-fiber-demo/pkg"
	"go-fiber-demo/pkg/utils"
	userService "go-fiber-demo/services/user"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"os"
	"strconv"
)

var app *cli.App

func NewCliApp() *cli.App {
	app = &cli.App{
		Name:  "Fiber Demo",
		Usage: "采用 fiber 实现的 api 服务器的基础骨架",
		Commands: []*cli.Command{
			initSuperAdmin(),
			startServer(),
		},
	}
	// 赋值
	pkg.GetConfig().CliApp = app

	return app
}

func StartCommand() {
	err := app.Run(os.Args)
	if err != nil {
		panic(err.Error())
	}
}

// 启动服务器
func startServer() *cli.Command {
	return &cli.Command{
		Name:    "startServe",
		Aliases: []string{"serve"},
		Usage:   "启动服务，请在创建超级管理员后执行此命令",
		Action: func(context *cli.Context) error {
			superUid := pkg.GetConfig().SuperUid
			if superUid == 0 {
				return cli.Exit("还没设置超级管理员，请先设置超级管理员后在启动服务", -4)
			}
			beforeStartServeFunc := pkg.GetConfig().AppConfig.BeforeStartServe
			NewApp(beforeStartServeFunc)

			return StartServe()
		},
	}
}

// 初始化超级管理员信息
func initSuperAdmin() *cli.Command {
	return &cli.Command{
		Name:    "initSuperAdmin",
		Aliases: []string{"init"},
		Usage:   "第一次启动项目前，应该用此条命令初始化管理员账号，并自动生成相关的信息",
		Flags: []cli.Flag{
			&cli.StringFlag{
				Name:     "username",
				Usage:    "管理员账号, 邮箱格式, 必填",
				Required: true,
			},
			&cli.StringFlag{
				Name:     "password",
				Usage:    "管理员密码， 6 - 32 位",
				Required: true,
			},
		},
		Action: func(context *cli.Context) error {
			superUid := pkg.GetConfig().SuperUid
			if superUid != 0 {
				return cli.Exit("已存在超级管理员配置，不要重复生成", -4)
			}

			superUser, err := userService.Register(context.String("username"), context.String("password"))
			if err != nil {
				return cli.Exit(err.Error(), -1)
			}
			fmt.Println("超级管理员注册成功, uid:" + strconv.Itoa(int(superUser.ID)))
			// 注册成功后注册相关权限
			initPermissions()
			// 创建成功后，写出超级管理员信息到配置中
			pkg.GetConfig().SuperUid = int(superUser.ID)
			// jwt 配置
			pkg.GetConfig().JwtConfig.Ext = 72
			pkg.GetConfig().JwtConfig.TokenSecret = utils.RandString(16)
			// aes 加密 key
			pkg.GetConfig().AppConfig.Key = utils.RandString(16)
			// 写出文件
			yamlBytes, err := yaml.Marshal(pkg.GetConfig())
			if err != nil {
				return cli.Exit(err.Error(), -2)
			} else {
				configFilePath := "./config/config.yaml"
				err = ioutil.WriteFile(configFilePath, yamlBytes, 0777)
				if err != nil {
					return cli.Exit(err.Error(), -2)
				} else {
					return cli.Exit("创建超级管理员并写出文件成功", 0)
				}
			}

		},
	}
}

func initPermissions() {
	// 权限相关
	permission := new(models.Permission)
	permission.Name = "PermissionAdd"
	permission.Description = "添加权限"
	permission.Url = "/admin/permissions"
	permission.Method = "post"
	permission.ModelName = ""
	permission.UrlParamName = ""
	permission.ModelCheckCondition = ""
	_ = permission.Add()
	permission = new(models.Permission)
	permission.Name = "PermissionList"
	permission.Description = "权限列表"
	permission.Url = "/admin/permissions"
	permission.Method = "get"
	permission.ModelName = ""
	permission.UrlParamName = ""
	permission.ModelCheckCondition = ""
	_ = permission.Add()
	permission = new(models.Permission)
	permission.Name = "PermissionEdit"
	permission.Description = "编辑权限"
	permission.Url = "/admin/permissions/:id"
	permission.Method = "put"
	permission.ModelName = ""
	permission.UrlParamName = ""
	permission.ModelCheckCondition = ""
	_ = permission.Add()
	permission = new(models.Permission)
	permission.Name = "PermissionDelete"
	permission.Description = "删除权限"
	permission.Url = "/admin/permissions/:id"
	permission.Method = "delete"
	permission.ModelName = ""
	permission.UrlParamName = ""
	permission.ModelCheckCondition = ""
	_ = permission.Add()
	permission = new(models.Permission)
	permission.Name = "PermissionDetail"
	permission.Description = "查看权限详情"
	permission.Url = "/admin/permissions/:id"
	permission.Method = "get"
	permission.ModelName = ""
	permission.UrlParamName = ""
	permission.ModelCheckCondition = ""
	_ = permission.Add()
	// 角色相关
	permission = new(models.Permission)
	permission.Name = "RuleAdd"
	permission.Description = "创建角色"
	permission.Url = "/admin/rules"
	permission.Method = "post"
	permission.ModelName = ""
	permission.UrlParamName = ""
	permission.ModelCheckCondition = ""
	_ = permission.Add()

	permission = new(models.Permission)
	permission.Name = "RuleList"
	permission.Description = "角色列表"
	permission.Url = "/admin/rules"
	permission.Method = "get"
	permission.ModelName = ""
	permission.UrlParamName = ""
	permission.ModelCheckCondition = ""
	_ = permission.Add()

	permission = new(models.Permission)
	permission.Name = "RuleEdit"
	permission.Description = "编辑角色"
	permission.Url = "/admin/rules/:id"
	permission.Method = "put"
	permission.ModelName = ""
	permission.UrlParamName = ""
	permission.ModelCheckCondition = ""
	_ = permission.Add()

	permission = new(models.Permission)
	permission.Name = "RuleDelete"
	permission.Description = "删除角色"
	permission.Url = "/admin/rules/:id"
	permission.Method = "delete"
	permission.ModelName = ""
	permission.UrlParamName = ""
	permission.ModelCheckCondition = ""
	_ = permission.Add()

	permission = new(models.Permission)
	permission.Name = "RuleDetail"
	permission.Description = "角色详情"
	permission.Url = "/admin/rules/:id"
	permission.Method = "get"
	permission.ModelName = ""
	permission.UrlParamName = ""
	permission.ModelCheckCondition = ""
	_ = permission.Add()
	// 用户
	permission = new(models.Permission)
	permission.Name = "UserAdd"
	permission.Description = "创建用户"
	permission.Url = "/admin/users"
	permission.Method = "post"
	permission.ModelName = ""
	permission.UrlParamName = ""
	permission.ModelCheckCondition = ""
	_ = permission.Add()

	permission = new(models.Permission)
	permission.Name = "UserList"
	permission.Description = "用户列表"
	permission.Url = "/admin/users"
	permission.Method = "get"
	permission.ModelName = ""
	permission.UrlParamName = ""
	permission.ModelCheckCondition = ""
	_ = permission.Add()

	permission = new(models.Permission)
	permission.Name = "UserEdit"
	permission.Description = "编辑用户"
	permission.Url = "/admin/users/:id"
	permission.Method = "put"
	permission.ModelName = ""
	permission.UrlParamName = ""
	permission.ModelCheckCondition = ""
	_ = permission.Add()

	permission = new(models.Permission)
	permission.Name = "UserDelete"
	permission.Description = "删除用户"
	permission.Url = "/admin/users/:id"
	permission.Method = "delete"
	permission.ModelName = ""
	permission.UrlParamName = ""
	permission.ModelCheckCondition = ""
	_ = permission.Add()

	permission = new(models.Permission)
	permission.Name = "UserDetail"
	permission.Description = "用户详情"
	permission.Url = "/admin/users/:id"
	permission.Method = "get"
	permission.ModelName = ""
	permission.UrlParamName = ""
	permission.ModelCheckCondition = ""
	_ = permission.Add()
}
